﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Data;
using System.Drawing.Imaging;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;

namespace AsianSocietyPictureUpload
{
    public partial class AsianSocietyUploadPicturesToDatabase
    {
        private void FixRawSatellite()
        {
            if (System.IO.Directory.Exists(rawsatellitePath))
            {
                string[] filePaths = Directory.GetFiles(rawsatellitePath);
                for (int i = 0; i < filePaths.Length; i++)
                {
                    try
                    {
                        file = filePaths[i].ToString();
                        fileName = System.IO.Path.GetFileName(filePaths[i].ToString());

                        string[] Nameindex = fileName.Split('_', '.');
                        string City = Nameindex[0];

                        if (fileName.Contains("Copy"))
                            City = "Guangzhou";

                        if (City != "")
                        {
                            string CityName = GetCityName(City);
                            int cityID = GetCitySatelliteID(CityName);

                            //Image rawImage;

                            //rawImage = CropImageFromRawSatellite(file);
                            //rawImage = ResizeImage(rawImage);
                            //rawImage = TextOverLayImageForRawSatellite(cityID, rawImage);

                            fileName = fileName.Replace(" - ", string.Empty);

                            //rawImage = SaveImageToLocalFolderSatelliteFromRaw(rawImage, fileName);
                            //rawImage.Dispose();
                            //rawImage = null;



                           

                            string day;

                            day = Nameindex[Nameindex.Length - 2];

                            if (Nameindex[Nameindex.Length - 2].Length > 2)
                                day = Nameindex[Nameindex.Length - 2].Substring(0, (Nameindex[Nameindex.Length - 2].Length - 1));

                            string Date = Nameindex[Nameindex.Length - 4] + '-' + Nameindex[Nameindex.Length - 3] + '-' + day;

                            InsertRawSatelliteToDatabase(cityID, fileName, Date);

                            //File.Delete(file);
                        }
                    }
                    catch { }
                }
            }
        }

        private void InsertRawSatelliteToDatabase(int CityID, string filePath, string date)
        {
            MySqlConnection mySQLCon = new MySqlConnection(setString.chinaairConnectionString);
            string sqlComand = "select mid from chinaair.tb_city_pollution where fcityid =" + CityID + " and zdate = '" + date + "'";

            mySQLCon.Open();

            MySqlCommand checkMID = new MySql.Data.MySqlClient.MySqlCommand(sqlComand, mySQLCon);

            MySqlDataReader dr = checkMID.ExecuteReader();


            int MID = 0;


            while (dr.Read())
            {
                MID = Convert.ToInt32(dr["mid"]);
            }

            dr.Close();

            if (MID > 0)
            {
                MySql.Data.MySqlClient.MySqlCommand updateMainImage = new MySql.Data.MySqlClient.MySqlCommand("UPDATE chinaair.tb_city_pollution  SET  comimg1 = 'display/sate/" + filePath + "', zenable = 'Y' WHERE MID =" + MID);

                updateMainImage.Connection = mySQLCon;
                updateMainImage.ExecuteNonQuery();
            }
            else
            {

                AsiaDBTableAdapters.tb_city_pollutionTableAdapter cityPolluA = new AsiaDBTableAdapters.tb_city_pollutionTableAdapter();

                cityPolluA.Insert("Y",
                                    Convert.ToDateTime(date),
                                    CityID,
                                    "0",
                                    "0",
                                    "0",
                                    "0",
                                    "0",
                                    "0",
                                    "",
                                    "display/sate/" +filePath,
                                    "",
                                    3,
                                    1,
                                    DateTime.Now.Date,
                                    5,
                                    DateTime.Now.Date,
                                    0,
                                    0);
            }
            mySQLCon.Close();
        }

        private int GetCitySatelliteID(string City)
        {
            switch (City)
            {
                case "CCNY":
                    return 7;
                case "Hangzhou":
                    return 5;
                case "HKPolyU":
                    return 6;
                case "UCSB":
                    return 8;
                case "La":
                    return 8;
                case "BONDVILLE":
                    return 11;
                case "Beijing":
                    return 3;
                case "NYC":
                    return 7;
                case "Chicago":
                    return 11;
                case "Guangzhou":
                    return 4;
                case "HK":
                    return 6;
                case "LA":
                    return 0;
                case "Shanghai":
                    return 5;
                case "New York":
                    return 7;
                case "Hong Kong":
                    return 6;
                case "Los Angeles":
                    return 8;
                case "Phoenix":
                    return 8;
                default:
                    return 0;
            }
        }

        private string GetCitySatelliteName(int id)
        {
            switch (id)
            {
                case 3:
                    return "Beijing";
                case 7:
                    return "NYC";
                case 11:
                    return "Chicago";
                case 4:
                    return "Guangzhou";
                case 5:
                    return "Shanghai";
                case 6:
                    return "Hong Kong";
                case 8:
                    return "Phoenix";
                default:
                    return "";
            }
        }


        private Image CropImageFromRawSatellite(string rawImagePath)
        {
            Bitmap bmpImage = new Bitmap(rawImagePath);

            double oldMargin = bmpImage.Height / (double)bmpImage.Width;
            double wantedMargin = 632 / (double)980;
            double newMargin;

            if (oldMargin > wantedMargin)
            {
                newMargin = oldMargin - wantedMargin;
            }
            else
            {
                newMargin = wantedMargin - oldMargin;
            }

            int x = Convert.ToInt32(bmpImage.Width);
            int y = Convert.ToInt32(bmpImage.Height * (1 - newMargin));

            Rectangle cropArea = new Rectangle(0, 0, x, y);

            Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);

            bmpImage.Dispose();
            bmpCrop.SetResolution(72.0F, 72.0F);

            return (Image)bmpCrop;
        }

        private Image TextOverLayImageForRawSatellite(int cityID , Image image)
        {
            foreach (DataRow row in dtCoord.Rows)
            {
                if (Convert.ToInt32(row["cityID"]) == cityID)
                {
                    int xCoord = Convert.ToInt32(row["x"]);
                    int yCoord = Convert.ToInt32(row["y"]);

                    Graphics g = Graphics.FromImage(image);

                    //Image b = Image.FromFile(@"d:\ChinaAirDaily_arrow glow5.png");

                    g.DrawImage(AsianSocietyPictureUpload.Properties.Resources.ChinaAirDaily_arrow_glow5, new Rectangle(xCoord-78, yCoord-60, 90, 48));
                    g.DrawImage(AsianSocietyPictureUpload.Properties.Resources.Satellite_icon, new Rectangle(0, 125, 150, 61));
                    g.Save();

                    g.Dispose();
                    break;
                }
            }
            return image;
        }

        private Image SaveImageToLocalFolderSatelliteFromRaw(Image image, string newFileName)
        {

            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;

            EncoderParameters myEncoderParameters = new EncoderParameters(1);

            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder,88L);
            myEncoderParameters.Param[0] = myEncoderParameter;

            if (image != null)
                image.Save(satellitePath + newFileName, jgpEncoder, myEncoderParameters);

            return image;
        }
























    }
}
